<template>
  <div class="posts-container">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-content">
        <div class="logo">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
          </svg>
        </div>
        <h1 class="title">社区动态</h1>
        <div class="user-info">
          <span class="username">{{ currentUser.username }}</span>
          <el-button @click="logout" type="text" class="logout-btn">退出</el-button>
        </div>
      </div>
    </header>

    <!-- 帖子列表 -->
    <main class="main-content">
      <div class="posts-list">
        <div 
          v-for="post in posts" 
          :key="post.id" 
          class="post-card"
          :class="{ 'liked': post.isLikedByUser }"
        >
          <!-- 帖子头部 -->
          <div class="post-header">
            <div class="author-info">
              <div class="author-avatar">
                <img :src="post.author.avatar" :alt="post.author.name" />
              </div>
              <div class="author-details">
                <h3 class="author-name">{{ post.author.name }}</h3>
                <p class="post-time">{{ formatTime(post.createdAt) }}</p>
              </div>
            </div>
            <el-button 
              v-if="post.author.id === currentUser.id"
              @click="deletePost(post.id)"
              type="danger" 
              size="small" 
              text
              class="delete-btn"
            >
              删除
            </el-button>
          </div>

          <!-- 帖子内容 -->
          <div class="post-content">
            <h2 class="post-title">{{ post.title }}</h2>
            <p class="post-text">{{ post.content }}</p>
            
            <!-- 帖子图片 -->
            <div v-if="post.images && post.images.length > 0" class="post-images">
              <img 
                v-for="(image, index) in post.images" 
                :key="index"
                :src="image" 
                :alt="`图片 ${index + 1}`"
                class="post-image"
                @click="previewImage(image, post.images, index)"
              />
            </div>
          </div>

          <!-- 帖子操作 -->
          <div class="post-actions">
            <div class="action-left">
              <el-button 
                @click="toggleLike(post.id)"
                :type="post.isLikedByUser ? 'danger' : 'default'"
                :class="{ 'liked-button': post.isLikedByUser }"
                class="like-btn"
                :loading="post.likeLoading"
              >
                <svg v-if="!post.isLikedByUser" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M20.84 4.61C20.3292 4.099 19.7228 3.69364 19.0554 3.41708C18.3879 3.14052 17.6725 2.99817 16.95 2.99817C16.2275 2.99817 15.5121 3.14052 14.8446 3.41708C14.1772 3.69364 13.5708 4.099 13.06 4.61L12 5.67L10.94 4.61C9.9083 3.5783 8.50903 2.9987 7.05 2.9987C5.59096 2.9987 4.19169 3.5783 3.16 4.61C2.1283 5.6417 1.5487 7.04097 1.5487 8.5C1.5487 9.95903 2.1283 11.3583 3.16 12.39L12 21.23L20.84 12.39C21.351 11.8792 21.7563 11.2728 22.0329 10.6053C22.3095 9.93789 22.4518 9.22248 22.4518 8.5C22.4518 7.77752 22.3095 7.06211 22.0329 6.39467C21.7563 5.72724 21.351 5.1208 20.84 4.61Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <svg v-else viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M20.84 4.61C20.3292 4.099 19.7228 3.69364 19.0554 3.41708C18.3879 3.14052 17.6725 2.99817 16.95 2.99817C16.2275 2.99817 15.5121 3.14052 14.8446 3.41708C14.1772 3.69364 13.5708 4.099 13.06 4.61L12 5.67L10.94 4.61C9.9083 3.5783 8.50903 2.9987 7.05 2.9987C5.59096 2.9987 4.19169 3.5783 3.16 4.61C2.1283 5.6417 1.5487 7.04097 1.5487 8.5C1.5487 9.95903 2.1283 11.3583 3.16 12.39L12 21.23L20.84 12.39C21.351 11.8792 21.7563 11.2728 22.0329 10.6053C22.3095 9.93789 22.4518 9.22248 22.4518 8.5C22.4518 7.77752 22.3095 7.06211 22.0329 6.39467C21.7563 5.72724 21.351 5.1208 20.84 4.61Z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <span class="like-text">{{ post.isLikedByUser ? '已点赞' : '点赞' }}</span>
                <span class="like-count" v-if="post.likesCount > 0">({{ post.likesCount }})</span>
              </el-button>

              <el-button class="comment-btn" text>
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M21 15C21 15.5304 20.7893 16.0391 20.4142 16.4142C20.0391 16.7893 19.5304 17 19 17H7L3 21V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H19C19.5304 3 20.0391 3.21071 20.4142 3.58579C20.7893 3.96086 21 4.46957 21 5V15Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                评论 ({{ post.commentsCount || 0 }})
              </el-button>
            </div>

            <div class="action-right">
              <el-button class="share-btn" text>
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 8C19.6569 8 21 6.65685 21 5C21 3.34315 19.6569 2 18 2C16.3431 2 15 3.34315 15 5C15 5.47784 15.0933 5.93314 15.2643 6.3445L8.73569 9.6555C8.09333 8.96828 7.19069 8.5 6 8.5C4.34315 8.5 3 9.84315 3 11.5C3 13.1569 4.34315 14.5 6 14.5C7.19069 14.5 8.09333 14.0317 8.73569 13.3445L15.2643 16.6555C15.0933 17.0669 15 17.5222 15 18C15 19.6569 16.3431 21 18 21C19.6569 21 21 19.6569 21 18C21 16.3431 19.6569 15 18 15C16.8093 15 15.9067 15.4683 15.2643 16.1555L8.73569 12.8445C8.90667 12.4331 9 11.9778 9 11.5C9 11.0222 8.90667 10.5669 8.73569 10.1555L15.2643 6.8445C15.9067 7.53172 16.8093 8 18 8Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                分享
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="80%"
      :before-close="handleImagePreviewClose"
    >
      <div class="image-preview-container">
        <img 
          :src="currentPreviewImage" 
          :alt="`图片预览`"
          class="preview-image"
        />
        <div v-if="previewImages && previewImages.length > 1" class="preview-navigation">
          <el-button @click="previousImage" :disabled="currentImageIndex === 0">上一张</el-button>
          <span class="image-counter">{{ currentImageIndex + 1 }} / {{ previewImages.length }}</span>
          <el-button @click="nextImage" :disabled="currentImageIndex === previewImages.length - 1">下一张</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPosts, likePost } from '@/api'
import { useUserStore } from '@/stores/user'

  // 定义类型
  interface Author {
    id: string
    name: string
    avatar: string
  }

  interface Post {
    id: string
    title: string
    content: string
    author: Author
    createdAt: string
    likesCount: number
    commentsCount: number
    isLikedByUser: boolean
    likeLoading?: boolean
    images?: string[]
  }

  interface User {
    id: string
    username: string
  }

  // const router = useRouter() // 使用routeUtils代替

// 当前用户信息（从 Pinia 获取）
const userStore = useUserStore()
const currentUser = reactive<User>({
  id: String(userStore.userId || '1'),
  username: String(userStore.userName || '用户')
})

  // 帖子列表
  const posts = ref<Post[]>([])

  // 图片预览相关
  const imagePreviewVisible = ref(false)
  const currentPreviewImage = ref('')
  const previewImages = ref<string[]>([])
  const currentImageIndex = ref(0)
// 点赞节流：记录每个帖子上次请求时间
const likeThrottleMap = new Map<string, number>()

// 初始化数据
onMounted(() => {
  // 同步最新用户数据
  currentUser.id = String(userStore.userId || '1')
  currentUser.username = String(userStore.userName || '用户')
  // 加载帖子数据
  loadPosts()
})

  // 加载帖子数据
async function loadPosts() {
  try {
    const res: any = await getPosts(currentUser.id)
    // 后端返回结构：{ code, message, data: [{ userLikeStatus: boolean, post: { postId, title, content, likeCount, userId }}, ...] }
    const list = Array.isArray(res.data) ? res.data : []
    posts.value = list.map((item: any) => {
      const p = item.post || {}
      const authorId = String(p.userId ?? '')
      return {
        id: String(p.postId ?? p.id ?? ''),
        title: String(p.title ?? ''),
        content: String(p.content ?? ''),
        author: {
          id: authorId,
          name: authorId === currentUser.id ? (currentUser.username || '当前用户') : `用户${authorId || ''}`,
          avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=100&h=100&fit=crop&crop=face'
        },
        createdAt: new Date().toISOString(),
        likesCount: Number(p.likeCount ?? 0),
        commentsCount: 0,
        isLikedByUser: Boolean(item.userLikeStatus),
        likeLoading: false,
        images: []
      }
    })
  } catch (e: any) {
    ElMessage.error(e?.message || '加载帖子失败')
  }
}

  // 切换点赞状态
  async function toggleLike(postId: string) {
    const post = posts.value.find(p => p.id === postId)
    if (!post) return

    // 3 秒内只能请求一次
    const now = Date.now()
    const last = likeThrottleMap.get(postId) || 0
    if (now - last < 1000) {
      return
    }
    likeThrottleMap.set(postId, now)

    post.likeLoading = true

    try {
      // 调用后端点赞/取消点赞接口
      const res: any = await likePost(postId, currentUser.id)
      // 期望返回：{ code, message, data: { userLikeStatus, postId, userId, likeCount } }
      const data = res.data || {}
      post.isLikedByUser = Boolean(data.userLikeStatus)
      post.likesCount = Number(data.likeCount ?? post.likesCount)
      ElMessage.success(post.isLikedByUser ? '点赞成功！' : '已取消点赞')
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    } finally {
      post.likeLoading = false
    }
  }

  // 删除帖子
  async function deletePost(postId: string) {
    try {
      await ElMessageBox.confirm('确定要删除这条帖子吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      const index = posts.value.findIndex(p => p.id === postId)
      if (index > -1) {
        posts.value.splice(index, 1)
        ElMessage.success('帖子已删除')
      }
    } catch (error) {
      // 用户取消删除
    }
  }

  // 格式化时间
  function formatTime(dateString: string): string {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return date.toLocaleDateString('zh-CN')
    }
  }

  // 图片预览
  function previewImage(image: string, images: string[], index: number) {
    currentPreviewImage.value = image
    previewImages.value = images
    currentImageIndex.value = index
    imagePreviewVisible.value = true
  }

  // 上一张图片
  function previousImage() {
    if (currentImageIndex.value > 0) {
      currentImageIndex.value--
      const image = previewImages.value[currentImageIndex.value]
      if (image) {
        currentPreviewImage.value = image
      }
    }
  }

  // 下一张图片
  function nextImage() {
    if (currentImageIndex.value < previewImages.value.length - 1) {
      currentImageIndex.value++
      const image = previewImages.value[currentImageIndex.value]
      if (image) {
        currentPreviewImage.value = image
      }
    }
  }

  // 关闭图片预览
  function handleImagePreviewClose() {
    imagePreviewVisible.value = false
    previewImages.value = []
    currentImageIndex.value = 0
  }

  // 退出登录
  function logout() {
    localStorage.removeItem('userInfo')
    ElMessage.success('已退出登录')
  }
</script>

<style scoped>
/* 主容器 */
.posts-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 头部样式 */
.header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 16px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.logo svg {
  width: 24px;
  height: 24px;
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
}

.logout-btn {
  color: #667eea;
  font-weight: 500;
}

.logout-btn:hover {
  color: #764ba2;
}

/* 主内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 帖子卡片 */
.post-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.post-card.liked {
  border-color: rgba(236, 72, 153, 0.3);
}

/* 帖子头部 */
.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(102, 126, 234, 0.2);
}

.author-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.author-name {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 4px 0;
}

.post-time {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.delete-btn {
  color: #ef4444;
}

/* 帖子内容 */
.post-content {
  margin-bottom: 20px;
}

.post-title {
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.post-text {
  font-size: 16px;
  color: #374151;
  line-height: 1.6;
  margin: 0 0 16px 0;
}

/* 帖子图片 */
.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-top: 16px;
}

.post-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 12px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.post-image:hover {
  transform: scale(1.02);
}

/* 帖子操作 */
.post-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.action-left {
  display: flex;
  gap: 16px;
}

.action-right {
  display: flex;
  gap: 8px;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.like-btn.liked-button {
  background: rgba(236, 72, 153, 0.1);
  color: #ec4899;
  border-color: rgba(236, 72, 153, 0.3);
}

.like-btn:hover {
  transform: translateY(-1px);
}

.like-btn svg {
  width: 18px;
  height: 18px;
}

.like-text {
  font-size: 14px;
  font-weight: 500;
}

.like-count {
  font-size: 12px;
  color: #666;
}

.comment-btn,
.share-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  color: #666;
  font-size: 14px;
}

.comment-btn svg,
.share-btn svg {
  width: 18px;
  height: 18px;
}

/* 图片预览 */
.image-preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.preview-navigation {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.image-counter {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    padding: 0 16px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .main-content {
    padding: 16px;
  }
  
  .post-card {
    padding: 20px;
  }
  
  .post-images {
    grid-template-columns: 1fr;
  }
  
  .post-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .post-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .post-title {
    font-size: 18px;
  }
  
  .post-text {
    font-size: 14px;
  }
  
  .like-btn,
  .comment-btn,
  .share-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>
